import Vue from 'vue'

import moment from 'moment'

Vue.prototype.$formattedDate = function (
  datetime,
  fI18n,
  locale,
  isUTC = false /* 是否UTC */,
  isDay = true /* 是否含有具体日期 */,
  isAbbr = false /* 是否简写 */
) {
  let values
  let time = datetime * 1000
  let monthArray = [
    'Jan',
    'Feb',
    'Mar',
    'Apr',
    'May',
    'Jun',
    'Jul',
    'Aug',
    'Sep',
    'Oct',
    'Nov',
    'Dec',
  ]
  let sDate
  if (isUTC) {
    sDate = moment(time).utc().format('YYYY-MM-DD')
  } else {
    sDate = moment(time).format('YYYY-MM-DD')
  }

  let sDateArry = sDate.split('-')
  let sMonth = monthArray[moment(time).get('month')]

  if (locale === 'zh' || locale === 'tw') {
    values = isDay
      ? `${sDateArry[0]}年${fI18n(sMonth)}${parseInt(sDateArry[2])}日`
      : `${sDateArry[0]}年${fI18n(sMonth)}`
  } else {
    values = isDay
      ? `${fI18n(isAbbr ? `${sMonth}_character` : sMonth)} ${sDateArry[2]} ${
          sDateArry[0]
        }`
      : `${fI18n(isAbbr ? `${sMonth}_character` : sMonth)} ${sDateArry[0]}`
  }
  return values
}

Vue.prototype.hasRealVal = function (val) {
  return val !== null && val !== '' && typeof val !== 'undefined'
}

Vue.prototype.getNameTextVal = function (list) {
  let listText = ''
  if (list && list.length > 0) {
    list.forEach((item) => {
      listText = `${listText}${listText !== '' ? ', ' : ''}${item.name}`
    })
  }
  return listText
}

Vue.prototype.$vReset = function (value) {
  if (typeof value === 'number' && !isNaN(value)) {
    let isnegative = value < 0
    let val = Math.abs(value)
    let res
    if (val <= 1000) {
      res = val
    } else if (val > 1000 && val < 1000000) {
      res = (val / 1000).toFixed(1) + 'K'
    } else if (val >= 1000000 && val < 1000000000) {
      res = (val / 1000000).toFixed(1) + 'M'
    } else {
      res = (val / 1000000000).toFixed(1) + 'B'
    }
    return isnegative ? `-${res}` : res
  } else if (typeof value === 'string' && !isNaN(parseFloat(value))) {
    // 如果传入的是字符串且可以转化为数值，则进行转化
    return this.$vReset(parseFloat(value))
  } else {
    return value ? value : 0
  }
}

Vue.prototype.$vResetPic = function (url, size = 500) {
  let iSrc = url
  if (iSrc && iSrc.indexOf('x-oss-process') === -1) {
    iSrc = `${iSrc}${
      iSrc.indexOf('?') === -1 ? '?' : '&'
    }x-oss-process=image/resize,l_${size},m_lfit`
  }
  if (
    iSrc &&
    iSrc.indexOf('https://nav-station.oss-accelerate.aliyuncs.com') >= 0
  ) {
    iSrc = iSrc.replace(
      'https://nav-station.oss-accelerate.aliyuncs.com',
      'https://cdn-images.toolify.ai'
    )
  }
  return iSrc
}

Vue.prototype.$websiteName = function (tool) {
  let toolName = tool.name
  if (tool.website_name) {
    toolName = tool.website_name
  }
  return toolName
}
